package com.agent.platform.service;

import com.agent.platform.dto.SessionStatusResponse;
import com.agent.platform.entity.Agent;
import com.agent.platform.entity.AgentSession;
import com.agent.platform.repository.AgentSessionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Agent会话服务 - 核心执行逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AgentSessionService {

    private final AgentSessionRepository sessionRepository;
    private final AgentService agentService;
    private final SessionLoopService sessionLoopService;

    /**
     * 启动会话
     */
    @Transactional
    public AgentSession startSession(String agentId, String sessionId, Map<String, Object> metadata) {
        Agent agent = agentService.getAgent(agentId);

        // 检查或创建会话
        AgentSession session = sessionRepository.findByAgentIdAndSessionId(agentId, sessionId)
            .orElseGet(() -> {
                AgentSession newSession = new AgentSession();
                newSession.setAgentId(agentId);
                newSession.setSessionId(sessionId);
                newSession.setMetadata(metadata);
                return newSession;
            });

        if (session.isRunning()) {
            throw new IllegalStateException("Session already running: " + sessionId);
        }

        session.markAsRunning();
        AgentSession started = sessionRepository.save(session);

        log.info("Started session: {} for agent: {}", sessionId, agentId);

        // 异步启动会话监听循环（通过独立Service实现真正的异步）
        sessionLoopService.startSessionLoop(agent, started);

        return started;
    }

    /**
     * 停止会话
     */
    @Transactional
    public AgentSession stopSession(String agentId, String sessionId, String reason) {
        AgentSession session = getSession(agentId, sessionId);

        // 停止循环
        sessionLoopService.stopSessionLoop(sessionId);

        session.markAsStopped();
        AgentSession stopped = sessionRepository.save(session);

        log.info("Stopped session: {} for agent: {} reason: {}", sessionId, agentId, reason);

        return stopped;
    }

    /**
     * 获取会话状态
     */
    public SessionStatusResponse getSessionStatus(String agentId, String sessionId) {
        AgentSession session = getSession(agentId, sessionId);

        return SessionStatusResponse.builder()
            .sessionId(session.getSessionId())
            .agentId(session.getAgentId())
            .status(session.getStatus())
            .stepCount(session.getStepCount())
            .failureCount(session.getFailureCount())
            .totalTokens(session.getTotalTokens())
            .totalCost(session.getTotalCost())
            .lastError(session.getLastError())
            .startedAt(session.getStartedAt())
            .stoppedAt(session.getStoppedAt())
            .metadata(session.getMetadata())
            .build();
    }

    /**
     * 列出Agent的所有会话
     */
    public List<AgentSession> listSessions(String agentId) {
        return sessionRepository.findByAgentId(agentId);
    }

    /**
     * 获取会话
     */
    private AgentSession getSession(String agentId, String sessionId) {
        return sessionRepository.findByAgentIdAndSessionId(agentId, sessionId)
            .orElseThrow(() -> new IllegalArgumentException(
                "Session not found: " + sessionId + " for agent: " + agentId));
    }
}
